<?php

namespace App\Console\Commands;

use App\Models\Member;
use App\Models\Room;
use Illuminate\Console\Command;
use App\Models\Card;


class Swoole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    private $serv;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Card $card, Member $member, Room $room)
    {
        parent::__construct();
        $this->card = $card;
        $this->member = $member;
        $this->room = $room;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //创建websocket服务器对象，监听0.0.0.0:9502端口
        $serv = new \swoole_websocket_server("0.0.0.0", 9502);
        $serv->on('Open', array($this, 'onOpen'));
        $serv->on('Message', array($this, 'onMessage'));
        $serv->on('Close', array($this, 'onClose'));
        $serv->start();
    }

    ///监听WebSocket连接打开事件
    public function onOpen($serv, $request)
    {
//        $GLOBALS['fd'][] = $request->fd;
//        $serv->push($request->fd, "hello, welcome 用户<$request->fd>\n");
    }

    //监听WebSocket消息事件
    public function onMessage($serv, $frame)
    {
        $data = object_array(json_decode($frame->data));
        var_dump($data);
        if (isset($data['type'])) {
            $this->executeMode($serv, $frame->fd, $data);
        }
    }

    //监听WebSocket连接关闭事件
    public function onClose($serv, $fd)
    {
        echo "/-------------------------fd： $fd 掉线啦\n";
        $this->offLine($serv, $fd);
        echo "client-{$fd} is closed\n";
    }

    public function executeMode($serv, $fd, $data)
    {
        $type = $data['type'];
        //$type : 0.解散游戏  1.加入游戏  2.加漂  3.落座  4.开始游戏  5.出牌  6.摸牌 7.检查胡杠碰 8.亮牌  9.掉线
        switch($type) {
            case 0 :
                //
                break;
            case 1 :
                $this->joinGame($serv, $fd, $data['rid'], $data['mid'], $data['role']);
                break;
            case 2 :
                $this->addPiao($serv, $fd, $data['rid'], $data['mid'], $data['role'], $data['piao']);
                break;
            case 3 :
                $this->setSite($serv, $fd, $data['rid'], $data['mid'], $data['role']);
                break;
            case 4 :
                $this->startGame($serv, $data['rid']);
                break;
            case 5 :
                $this->sendCard($serv, $fd, $data['rid'], $data['cid'], $data['id'], $data['next']);
                break;
            case 6 :
                $this->getCard($serv, $fd, $data['rid']);
                break;
            case 7 :
                $this->checkStatus($serv, $fd, $data['rid'], $data['cid'], $data['id'], $data['pre'], $data['next'], $data['status']);
                break;
            case 8 :
                $this->hupai($serv, $fd, $data['rid'], $data['hu'], $data['role']);
                break;
            case 9 :
//                $this->offLine()
                break;
				
			case 18 :
                $this->checkHu($serv, $fd, $data['rid'], $data['cards']);
                break;
            case 19 :
                $this->checkLiang($serv, $fd, $data['rid'], $data['cards']);
                break;
        }
    }

    public function getCard($serv, $fd, $rid)
    {
        $this->sendMsg2others($serv, $fd, $rid, json_encode(['type'=>6]));
    }

    public function joinGame($serv, $fd, $rid, $mid, $role)
    {
        $this->room->storeRoomInfo($fd, $rid, $mid, $role, 1);
        $data['member'] = $this->member->getMember($mid);
        $data['type'] = 1;
        $data['role'] = $role;
        $players = $this->getRoomInfo($rid);
        $pnum = count($players);
        if ($pnum == 3) {
            $data['status'] = 1;
            $this->sendMsg2All($serv, $rid, json_encode($data));
        } else {
            $this->sendMsg2others($serv, $fd, $rid, json_encode($data));
        }
    }

    public function addPiao($serv, $fd, $rid, $mid, $role, $piao='')
    {
        $this->room->storeRoomInfo($fd, $rid, $mid, $role, 2, $piao);
        $players = $this->getRoomInfo($rid);
//        var_dump($players);
        if (($players['host']['piao'] != '') && ($players['r1']['piao'] != '') && ($players['r2']['piao'] != '')) {
            $this->sendMsg2All($serv, $rid, json_encode(['type'=>2]));
        }
    }

    public function sendMsg($serv, array $fds, $data)
    {
        foreach ($fds as $v) {
            $serv->push($v,$data);
        }
    }


    public function setSite($serv, $fd, $rid, $mid, $role)
    {
        $this->room->storeRoomInfo($fd, $rid, $mid, $role, 1);
        $players = $this->getRoomInfo($rid);
        var_dump($players);
        $host = isset($players['host']['status']) ? $players['host']['status'] : 0;
        $r1 = isset($players['r1']['status']) ? $players['r1']['status'] : 0;
        $r2 = isset($players['r2']['status']) ? $players['r2']['status'] : 0;
//        var_dump($players);
        if ($host && $r1 && $r2) {
            $this->startGame($serv, $rid, $players);
        } else {
            $this->sendMsg2All($serv, $rid, json_encode(['type'=>3]));
        }
        echo $role."\n";
    }


    public function startGame($serv, $rid, $players='')
    {
        if (!$players) {
            $players = $this->getRoomInfo($rid);
        }
//        $banker = $this->getBanker($players);
//        $cards = $this->card->dealCard($banker);
        $cards = $this->card->dealCard('host');
//        var_dump($players);
        foreach ($players as $v) {
            $serv->push($v['fd'],$cards);
        }
    }

    public function getRoomInfo($rid)
    {
        $players = $this->room->getRoomInfo($rid);
        return $players;
    }

    public function sendCard($serv, $fd, $rid, $cid, $id, $next)
    {
        $data = json_encode(['cid'=>$cid, 'id'=>$id, 'type'=>5, 'next'=>$next]);
//        var_dump($data);/
        $this->sendMsg2others($serv, $fd, $rid, $data);
    }

    public function delFd($fd, $rid)
    {
        $players = $this->getRoomInfo($rid);
        foreach ($players as $k=>$v) {
            if ($fd == $v['fd']) {
                echo $v['fd'];
                unset($players[$k]);
            }
        }
    }

    public function offLine($serv, $fd)
    {
        $rid = $this->room->getRidByFd($fd);
        $players = $this->getRoomInfo($rid);
        $data['type'] = 9;
        foreach ($players as $k=>$v) {
            if ($fd == $v['fd']) {
                $data['role'] = $k;
                $players[$k]['fd'] = 0;
            }
        }
//        var_dump($players);
        echo "处理掉线\n";
        $this->room->resetRoomInfo($rid, $players);
//        var_dump($players);
//        $this->sendMsg2others($serv, $fd, $rid, json_encode($data));
    }

    public function sendMsg2others($serv, $fd, $rid, $data)
    {
        $players = $this->getRoomInfo($rid);
        echo $fd."\n";
//        var_dump($players);
        foreach ($players as $k=>$v) {
            if (($fd != $v['fd']) && !empty($v['fd'])) {
                echo $k."\n";
                $serv->push($v['fd'],$data);
            }
        }
    }

    public function sendMsg2All($serv, $rid, $data)
    {
        var_dump($data);
        $players = $this->getRoomInfo($rid);
//        var_dump($players);
        foreach ($players as $k=>$v) {
            if ($v['fd']) {
                echo $k."\n";
                $serv->push($v['fd'],$data);
            }
        }
    }

    public function hupai($serv, $fd, $rid, $hu, $role)
    {
        $this->sendMsg2others($serv, $fd, $rid, json_encode(['type'=>8]));
    }


    public function getBanker($players)
    {
        $piao['host'] = $players['host']['piao'];
        $piao['r1'] = $players['r1']['piao'];
        $piao['r2'] = $players['r2']['piao'];

        $time['host'] = $players['host']['piao_time'];
        $time['r1'] = $players['r1']['piao_time'];
        $time['r2'] = $players['r2']['piao_time'];
        $maxpiao = max($piao);
        if ($maxpiao > 0) {
            foreach ($piao as $k=>$v) {
                if($v < $maxpiao) {
                    unset($piao[$k]);
                    unset($time[$k]);
                }
            }
        }
        $mintime = min($time);
        foreach ($time as $k=>$v) {
            if($v == $mintime) {
                return $k;
            }
        }
    }

    public function checkStatus($serv, $fd, $rid, $cid, $id, $pre, $next, $status)
    {
        $this->room->storeStatus($rid, $status);
        $data['type'] = 5;
        $data['cid'] = $cid;
        $data['id'] = $id;
        $data['pre'] = $pre;
        $data['next'] = $next;
        switch ($status) {
            case 0 :
                //0
                $arr = $this->room->getStatus($rid);
                var_dump($arr);
                if (isset($arr[0]) && isset($arr[1])) {
                    if (($arr[0] == 0) && ($arr[1] == 0)) {
                        $data['res'] = 0;
//                        $this->sendMsg2others($serv, $fd, $rid, json_encode($data));
                        $this->room->delStatus($rid);
                        var_dump($this->room->getStatus($rid));
                        $this->sendMsg2All($serv, $rid, json_encode($data));
                    }
                }
                break;
            case 1 :
                //胡
                $data['res'] = 1;
                $this->room->delStatus($rid);
                var_dump($this->room->getStatus($rid));
                $this->sendMsg2All($serv, $rid, json_encode($data));
                break;
            case 2 :
                //杠
                $data['res'] = 2;
                $this->room->delStatus($rid);
                var_dump($this->room->getStatus($rid));
                $this->sendMsg2All($serv, $rid, json_encode($data));
                break;
            case 3 :
                //碰
                $data['res'] = 3;
                $this->room->delStatus($rid);
                var_dump($this->room->getStatus($rid));
                $this->sendMsg2All($serv, $rid, json_encode($data));
                break;

        }
    }
	
	public function checkHu($serv, $fd, $rid, $cards)
	{
		$res = hu($cards);
        $arr['res'] = $res;
//		if (!$res) {
//            $arr['res'] = 0;
//		}
        $arr['type'] = 18;
		$serv->push($fd,json_encode($arr));
	}

    public function checkLiang($serv, $fd, $rid, $cards)
    {
        $arr['type'] = 19;
        $arr['res'] = checkLiang($cards) ;
        var_dump($arr);
        $serv->push($fd,json_encode($arr));
    }

}
